$(function () {
    var queryUrl = '../devmaintenplan/list?isValid=1';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '&Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        rownumWidth: 35,
        height: 600,
        colModel: [
            // {label: '规程名称', name: 'ruleName', index: 'RULE_NAME', width: 100},
            {label: '版本', name: 'planVersion', index: 'PLAN_VERSION', width: 50},
            {label: '设备名称', name: 'deviceName', index: 'DI.DEV_NAME', width: 75},
            {label: '设备编码', name: 'deviceCode', index: 'DI.DEV_CODE', width: 55},
            {label: '单位', name: 'shop', index: 'WORKSHOP_ID', width: 60},
            {label: '区域', name: 'line', index: 'DEV_PRODUCT_NAME', width: 80},
            {label: '工序号', name: 'proce', index: 'DEV_PROCE_NO', width: 40},
            {
                label: '规程类型', name: 'reserve1', index: 'RESERVE_1', width: 35,
                formatter: function (value) {
                    if (value == "" || value == "null" || value == null) {
                        return "";
                    } else {
                        return sysEnums.MAINTENPLAN_TYPE[value];
                    }
                }
            },
            {
                label: '审核详情', width: 50, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;" + sysEnums.SPARE_NEEDS_PLAN_PROGRESS[row.progress] +"</button>";
                }
            },
            {
                label: '维护项', width: 40, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.viewOption(\"" + row.id + "\")'>&nbsp;详情</button>";
                }
            },
            {
                label: '版本', width: 30, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.viewVersion(\"" + row.devId + "\")'>&nbsp;查看</button>";
                }
            },
            {label: '设备编码', name: 'devCode', index: 'DEV_CODE', hidden: true},
            {name: 'id', key: true, hidden: true},
            {name: 'progress', hidden: true},
            {name: 'devId', hidden: true}
        ]
    });
    // 初始化设备组织结构树
    vm.initDeviceOrgList();
});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        },
    },
    callback: {
        beforeCheck: true,
    }

};
//设备组织树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: function (e, treeObj, treeNode) {
            vm.q.devLineId = treeObj.deptId;
            vm.query();
        }
    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        title_plan: '',
        devMaintenPlan: {
            ruleName: '',  // 规程名称
            devCode: '', // 设备编码
            devName: '', // 设备名称
            reserve1: '', // 规程类型
            planCon: '' // 内容
        },
        maintain_plan: {
            devId: '',
            dept: '',
            beltline: '',
            beltlineName: '',
        },
        typeList: enumsToList('MAINTENPLAN_TYPE'),//规程类型
        // freRateArray: enumsToList("FRERATE2"),   //频率类型
        v_showList: true,
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        ValidateResource: {
            planName: [
                {required: true, message: '计划名称不能为空', trigger: 'blur'}
            ],
            carryDate: [
                {required: true, message: '执行时间不能为空', trigger: 'blur'}
            ],
            dept: [
                {required: true, message: '所属机构不能为空', trigger: 'blur'}
            ],
            beltline: [
                {required: true, message: '生产线不能为空', trigger: 'blur'}
            ],
            completeDate: [
                {required: true, message: '完成时间不能为空', trigger: 'blur'}
            ],
        },
        q: {
            name: '',
            planVersion: '',
            devCode: '',
            workshop: '',
            progress: ''
        },
        deptList: [],
        beltlineList: [],
        // 审核参数VO
        approveParam: {
            approveIdList: [],
            status: 1,
            remark: ''
        },
        statusList: enumsToList('SPARE_NEEDS_PLAN_PROGRESS')
    },
    created: function () {

    },
    methods: {
        // 导出设备基础信息
        exportData: function () {
            // 查询条件数组：默认只导出有效的
            let queryConditionArray = ['isValid=1'];
            if (this.q.name) {
                queryConditionArray.push('name=' + this.q.name);
            }
            if (this.q.planVersion) {
                queryConditionArray.push('planVersion=' + this.q.planVersion);
            }
            if (this.q.devCode) {
                queryConditionArray.push('devCode=' + this.q.devCode);
            }
            if (this.q.progress) {
                queryConditionArray.push('progress=' + this.q.progress);
            }
            if (this.q.devLineId) {
                queryConditionArray.push('devLineId=' + this.q.devLineId);
            }
            window.open('../devmaintenplan/exportData?' + queryConditionArray.join('&'), '_blank');
        },
        initDeviceOrgList: function () {
            //加载部门树
            Ajax.request({
                url: '../sys/user/treeDeptBySCXLevel?level=3',
                async: false,
                successCallback: function (r) {
                    deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, r.list);
                    // 默认展开工厂一级
                    deptZtree.expandNode(deptZtree.getNodeByParam("deptId",'01',null));
                }
            });
        },
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../sys/user/treeDeptByType/DT_CJKSCX',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    ztree.expandAll(true);
                }
            });
        },
        deptTreeShow: function () {
            openWindow({
                title: "选择生产线",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    vm.maintain_plan.dept = node[0].parentId;
                    if (node[0].deptType == 'DT_CJKSCX') {
                        // //选择上级菜单
                        vm.maintain_plan.beltline = node[0].deptId;
                        vm.maintain_plan.beltlineName = node[0].name;
                        layer.close(index);
                    }
                }
            });
        },
        check: function () {
            // 必须选中记录
            var ruleIdList = [];
            var datas = getSelectedRowDatas("#jqGrid");
            for (let i = 0; i < datas.length; i++) {
                var data = datas[i];
                if (data.progress !== '1') {
                    alert("[" + data.ruleName + "]不是[部门审核中]的维护规程，请移除！");
                    return;
                }
                ruleIdList.push(data.id)
            }
            // 构建审批参数
            vm.approveParam = {
                approveIdList: ruleIdList,
                status: '1',
                remark: ''
            }
            openWindow({
                title: "审核信息",
                area: ['450px', '300px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    if (typeof (vm.approveParam.status) == 'undefined') {
                        alert("请选择审核状态");
                        return;
                    }
                    vm.updateCheck('../devmaintenplan/check', JSON.stringify(vm.approveParam));
                }
            });
        },
        okCheck: function () {
            // 必须选中记录
            var ruleIdList = [];
            var datas = getSelectedRowDatas("#jqGrid");
            for (let i = 0; i < datas.length; i++) {
                var data = datas[i];
                if (data.progress !== '2') {
                    alert("[" + data.ruleName + "]不是[PE审核中]的维护规程，请移除！");
                    return;
                }
                ruleIdList.push(data.id)
            }
            // 构建审批参数
            vm.approveParam = {
                approveIdList: ruleIdList,
                status: '1',
                remark: ''
            }
            openWindow({
                title: "确认审核",
                area: ['450px', '300px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    if (typeof (vm.approveParam.status) == 'undefined') {
                        alert("请选择审核状态");
                        return;
                    }
                    vm.updateCheck('../devmaintenplan/okCheck', JSON.stringify(vm.approveParam));
                }
            });
        },
        updateCheck: function (url, params) {
            Ajax.request({
                url: url,
                params: params,
                contentType: "application/json",
                type: 'POST',
                successCallback: function (res) {
                    alert('审核成功!', function () {
                        layer.closeAll();
                        vm.reload();
                    });
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.devMaintenPlan = {
                ruleName: '',  // 规程名称
                planVersion: '', // 版本号
                devCode: '', // 设备编码
                devName: '', // 设备名称
                reserve1: 2, // 规程类型
                planCon: '' // 内容
            };
        },
        //审核详情
        shviewOption: function (res) {
            var data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    var approveProcessList = res.approveProcessList;
                    if (approveProcessList.length == 0) {
                        iview.Message.error("暂无审批记录");
                        return;
                    }
                    var dom = "<div class='details'><table>";
                    for (var i = 0; i < approveProcessList.length; i++) {
                        var approveProcess = approveProcessList[i];
                        dom += '<tr><td>' + approveProcess.approveDate + '</td>';
                        dom += '<td align="left">' + approveProcess.roleName + '-' + approveProcess.name + '： ' + sysEnums.CHECK_FLAG[approveProcess.status];
                        if (approveProcess.remark) {
                            dom += '<br />备注：' + approveProcess.remark;
                        }
                        dom += '</td></tr>'
                    }
                    dom += '</table></div>'
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['500px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: dom
                    });
                }
            });
        },
        //查看详情
        viewOption: function (plan_id) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-file-text-o"></i> 查看详情',
                content: '../device/devmaintenplanView.html?plan_id=' + plan_id
            })
        },
        //查看规程版本
        viewVersion: function (devId) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-file-text-o"></i> 版本记录',
                content: '../device/devmaintenplanHistory.html?devId=' + devId
            })
        },
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.devMaintenPlan.devCode = res.devCode;
                        vm.devMaintenPlan.devName = res.devName;
                        vm.devMaintenPlan.devId = res.id;
                        layer.close(index);
                    }
                }
            })
        },
        deptListData: function (value) {
        },
        judgeAndLower: function () {
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            vm.getTreeShow();
            vm.deptList = [];
            $.ajax({
                url: '../sysMsg/queryDept',
                type: 'GET',
                success: function (value) {
                    if (value.deptList.length > 0) {
                        for (var list in value.deptList) {
                            if (value.deptList.hasOwnProperty(list)) {
                                vm.deptList.push(value.deptList[list]);
                            }
                        }
                    }
                }
            })
            vm.maintain_plan.devId = id;
            $.ajax({
                url: '../maintainplan/queryModulMaintianId',
                type: 'GET',
                data: {"id": id},
                success: function (res) {
                    if (res.msg) {
                        alert(res.msg, "function");
                    } else {
                        vm.title_plan = '评判并下发';
                        openWindow({
                            title: '创建维护计划',
                            area: ['40%', '90%'],
                            content: jQuery("#planData"),
                            btn: ['确定', '取消'],
                            btn1: function (index) {
                                Ajax.request({
                                    url: '../maintainplan/inMaintain',
                                    type: 'POST',
                                    params: vm.maintain_plan,
                                    successCallback: function (allData) {
                                        layer.close(index)
                                        vm.maintain_plan = {}
                                    }
                                })
                            },
                            btn2: function (index) {
                                vm.maintain_plan = {}
                            }
                        })
                    }
                }
            });
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            var url = vm.devMaintenPlan.id == null ? "../devmaintenplan/save" : "../devmaintenplan/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.devMaintenPlan),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.devMaintenPlan = {delFlag: 0, id: id};
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devmaintenplan/updateDel",
                    params: JSON.stringify(vm.devMaintenPlan),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devmaintenplan/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.devMaintenPlan = r.devMaintenPlan;
                    var type = vm.devMaintenPlan.reserve1;
                    vm.devMaintenPlan.reserve1 = Number(type);
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                search: true,
                postData: vm.q,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                devCode: '',
                workshop: '',
                progress: '',
                devLineId: '',
                planVersion: ''
            };
            // 取消选中
            deptZtree.cancelSelectedNode();
            // 重新加载数据
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
            vm.handleResetRem('formValidateResource');
        },
        handleResetRem: function (name) {
            handleResetForm(this, name);
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert('导入结果：' + res.err, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleError: function (err, file) {
            alert('导入失败');
        }
    }
});
